package com.rj.bd.utils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class EmailUtil {
	 //发送者自己的邮箱
	public static String sendEmailAccount ="zjl20020307@163.com";
	//邮箱授权码
	public static String sendEmailPwd="SOQODJBGDDIHMXXQ";
	/**
	 * @desc  0.将发送邮件的前3步抽取成一个函数，目的是方便后续的代码的复用
	 * @return
	 */
	private static Session getSession()
	{
		//1.创建参数配置, 用于连接邮件服务器的参数配置
		Properties props=new Properties();
	    props.setProperty("mail.transport.protocol","smtp");// 使用的协议（JavaMail规范要求）
	    props.setProperty("mail.smtp.host","smtp.163.com"); // 发件人的邮箱的 SMTP 服务器地址
	    props.setProperty("mail.smtp.auth", "true");    // 需要请求认证
		
		// 2. 根据配置创建会话对象, 用于和邮件服务器交互
		Session session=Session.getInstance(props);
		//session.setDebug(true);//以debug的模式进行运行，方便后续出错误时候的调试
		return session;
	}
	public static void createMineMessage(String receiveMailCount,String username,String emailsubject,String context) throws UnsupportedEncodingException, MessagingException{
		Session session = getSession();
		//根据session创建一封邮件
		MimeMessage  message=new MimeMessage(session);
		//4.From:发件人
		message.setFrom(new InternetAddress(sendEmailAccount, "忘记密码重置", "utf-8"));
		message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMailCount, username, "utf-8"));
		
		message.setSubject(emailsubject);
		
		message.setContent(context, "text/html;charset=utf-8");
		saveAndSendEmail(message, session);
	}
	private static void saveAndSendEmail(MimeMessage message, Session session) throws MessagingException {
		message.setSentDate(new Date());
		message.saveChanges();
		Transport transport = session.getTransport();
		//11.连接SMTP服务器
		transport.connect(sendEmailAccount, sendEmailPwd);
		
		// 12. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
		transport.sendMessage(message, message.getAllRecipients());
		
		  // 13. 关闭连接
		transport.close();	
		
	}
}
